<!DOCTYPE html>
<html lang=zh-CN>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="og:description" content="samuel-24276的博客">
    <meta property="og:type" content="website">
    <meta name="description" content="samuel-24276的博客">
    <meta name="keyword"  content="aircloud">
    <link rel="shortcut icon" href="/myblog/img/favicon.ico">

    <title>
        
        JavaScript学习日记（3） - samuel-24276的博客 | samuel-24276&#39;s Blog
        
    </title>

    <!-- Custom CSS -->
    
<link rel="stylesheet" href="/myblog/css/aircloud.css">

    
<link rel="stylesheet" href="/myblog/css/gitment.css">

    <!--<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">-->
    <link href="//at.alicdn.com/t/font_620856_28hi1hpxx24.css" rel="stylesheet" type="text/css">
    <!-- ga & ba script hoook -->
    <script></script>
<meta name="generator" content="Hexo 7.1.1"></head>

<body>

<div class="site-nav-toggle" id="site-nav-toggle">
    <button>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
    </button>
</div>

<div class="index-about">
    <i> Like what you do, do what you like </i>
</div>

<div class="index-container">
    
    <div class="index-left">
        
<div class="nav" id="nav">
    <div class="avatar-name">
        <div class="avatar ">
            <img src="/myblog/img/avatar.jpg" />
        </div>
        <div class="name">
            <i>samuel-24276</i>
        </div>
    </div>
    <div class="contents" id="nav-content">
        <ul>
            <li >
                <a href="/myblog/">
                    <i class="iconfont icon-shouye1"></i>
                    <span>主页</span>
                </a>
            </li>
            <li >
                <a href="/myblog/tags">
                    <i class="iconfont icon-biaoqian1"></i>
                    <span>标签</span>
                </a>
            </li>
            <li >
                <a href="/myblog/archives">
                    <i class="iconfont icon-guidang2"></i>
                    <span>存档</span>
                </a>
            </li>
            <li >
                <a href="/myblog/collect/">
                    <i class="iconfont icon-shoucang1"></i>
                    <span>收藏</span>
                </a>
            </li>
            <li >
                <a href="/myblog/about/">
                    <i class="iconfont icon-guanyu2"></i>
                    <span>关于</span>
                </a>
            </li>
            
            <li>
                <a id="search">
                    <i class="iconfont icon-sousuo1"></i>
                    <span>搜索</span>
                </a>
            </li>
            
        </ul>
    </div>
    
        <div id="toc" class="toc-article">
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%AF%B9%E8%B1%A1"><span class="toc-text">使用对象</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E6%A6%82%E8%BF%B0"><span class="toc-text">对象概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E5%92%8C%E5%B1%9E%E6%80%A7"><span class="toc-text">对象和属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9E%9A%E4%B8%BE%E4%B8%80%E4%B8%AA%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%89%80%E6%9C%89%E5%B1%9E%E6%80%A7"><span class="toc-text">枚举一个对象的所有属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E6%96%B0%E5%AF%B9%E8%B1%A1-notebook"><span class="toc-text">创建新对象:notebook:</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%AF%B9%E8%B1%A1%E5%88%9D%E5%A7%8B%E5%8C%96%E5%99%A8"><span class="toc-text">使用对象初始化器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"><span class="toc-text">使用构造函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-Object-create-%E6%96%B9%E6%B3%95"><span class="toc-text">使用 Object.create 方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%A7%E6%89%BF"><span class="toc-text">继承</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E5%B1%9E%E6%80%A7%E7%B4%A2%E5%BC%95"><span class="toc-text">对象属性索引</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BA%E5%AF%B9%E8%B1%A1%E7%B1%BB%E5%9E%8B%E5%AE%9A%E4%B9%89%E5%B1%9E%E6%80%A7"><span class="toc-text">为对象类型定义属性</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89%E6%96%B9%E6%B3%95"><span class="toc-text">定义方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%80%9A%E8%BF%87-this-%E5%BC%95%E7%94%A8%E5%AF%B9%E8%B1%A1"><span class="toc-text">通过 this 引用对象</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89-getter-%E4%B8%8E-setter"><span class="toc-text">定义 getter 与 setter</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E5%B1%9E%E6%80%A7"><span class="toc-text">删除属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AF%94%E8%BE%83%E5%AF%B9%E8%B1%A1"><span class="toc-text">比较对象</span></a></li></ol></li></ol>
</div>
    
</div>


<div class="search-field" id="search-field">
    <div class="search-bg" id="search-bg"></div>
    <div class="search-container">
        <div class="search-input">
            <span id="esc-search"> <i class="icon-fanhui iconfont"></i></span>
            <input id="search-input"/>
            <span id="begin-search">搜索</span>
        </div>
        <div class="search-result-container" id="search-result-container">

        </div>
    </div>
</div>

        <div class="index-about-mobile">
            <i> Like what you do, do what you like </i>
        </div>
    </div>
    
    <div class="index-middle">
        <!-- Main Content -->
        


<div class="post-container">
    <div class="post-title">
        JavaScript学习日记（3）
    </div>

    <div class="post-meta">
        <span class="attr">发布于：<span>2023-04-30 08:20:13</span></span>
        
        <span class="attr">标签：/
        
        <a class="tag" href="/myblog/tags/#前端" title="前端">前端</a>
        <span>/</span>
        
        <a class="tag" href="/myblog/tags/#JS" title="JS">JS</a>
        <span>/</span>
        
        
        </span>
        <span class="attr">访问：<span id="busuanzi_value_page_pv"></span>
</span>
</span>
    </div>
    <div class="post-content no-indent">
        <h1 id="使用对象"><a href="#使用对象" class="headerlink" title="使用对象"></a>使用对象</h1><p>JavaScript 的设计是一个简单的基于对象的范式。<strong>一个对象就是一系列属性的集合，一个属性包含一个名和一个值。一个属性的值可以是函数，这种情况下属性也被称为<em>方法</em></strong>。除了浏览器里面预定义的那些对象之外，你也可以定义你自己的对象。本章节讲述了怎么使用对象、属性、函数和方法，怎样实现自定义对象。</p>
<h2 id="对象概述"><a href="#对象概述" class="headerlink" title="对象概述"></a>对象概述</h2><p>javascript 中的对象 (物体)，和其他编程语言中的对象一样，可以比照现实生活中的对象 (物体) 来理解它。</p>
<p>在 javascript 中，一个对象可以是一个单独的拥有属性和类型的实体。我们拿它和一个杯子做下类比。一个杯子是一个对象 (物体)，拥有属性。杯子有颜色，图案，重量，由什么材质构成等等。同样，javascript 对象也有属性来定义它的特征。</p>
<h2 id="对象和属性"><a href="#对象和属性" class="headerlink" title="对象和属性"></a>对象和属性</h2><p>一个 javascript 对象有很多属性。一个对象的属性可以被解释成一个附加到对象上的变量。对象的属性和普通的 javascript 变量基本没什么区别，仅仅是属性属于某个对象。属性定义了对象的特征。你可以通过点符号来访问一个对象的属性。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">objectName.<span class="property">propertyName</span></span><br></pre></td></tr></table></figure>

<p>和其他 javascript 变量一样，对象的名字 (可以是普通的变量) 和属性的名字都是<strong>大小写敏感</strong>的。你可以在定义一个属性的时候就给它赋值。例如，我们创建一个 myCar 的对象然后给他三个属性，make，model，year。具体如下所示：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> myCar = <span class="keyword">new</span> <span class="title class_">Object</span>();</span><br><span class="line">myCar.<span class="property">make</span> = <span class="string">&quot;Ford&quot;</span>;</span><br><span class="line">myCar.<span class="property">model</span> = <span class="string">&quot;Mustang&quot;</span>;</span><br><span class="line">myCar.<span class="property">year</span> = <span class="number">1969</span>;</span><br></pre></td></tr></table></figure>

<p>对象中未赋值的属性的值为<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/undefined"><code>undefined</code></a>（而不是<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/null"><code>null</code></a>）。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">myCar.<span class="property">noProperty</span>; <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>

<p>JavaScript 对象的属性也可以通过方括号访问或者设置（更多信息查看 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Property_accessors">property accessors</a>）. <strong>对象有时也被叫作关联数组，因为每个属性都有一个用于访问它的字符串值</strong>。例如，你可以按如下方式访问 <code>myCar</code> 对象的属性：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">myCar[<span class="string">&quot;make&quot;</span>] = <span class="string">&quot;Ford&quot;</span>;</span><br><span class="line">myCar[<span class="string">&quot;model&quot;</span>] = <span class="string">&quot;Mustang&quot;</span>;</span><br><span class="line">myCar[<span class="string">&quot;year&quot;</span>] = <span class="number">1969</span>;</span><br></pre></td></tr></table></figure>

<p>一个对象的属性名可以是任何有效的 JavaScript 字符串，或者可以被转换为字符串的任何类型，包括空字符串。然而，<strong>一个属性的名称如果不是一个有效的 JavaScript 标识符（例如，一个由空格或连字符，或者以数字开头的属性名），就只能通过方括号标记访问</strong>。这个标记法在属性名称是动态判定（属性名只有到运行时才能判定）时非常有用。例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 同时创建四个变量，用逗号分隔</span></span><br><span class="line"><span class="keyword">var</span> myObj = <span class="keyword">new</span> <span class="title class_">Object</span>(),</span><br><span class="line">    str = <span class="string">&quot;myString&quot;</span>,</span><br><span class="line">    rand = <span class="title class_">Math</span>.<span class="title function_">random</span>(),</span><br><span class="line">    obj = <span class="keyword">new</span> <span class="title class_">Object</span>();</span><br><span class="line"></span><br><span class="line">myObj.<span class="property">type</span>              = <span class="string">&quot;Dot syntax&quot;</span>;</span><br><span class="line">myObj[<span class="string">&quot;date created&quot;</span>]   = <span class="string">&quot;String with space&quot;</span>;</span><br><span class="line">myObj[str]              = <span class="string">&quot;String value&quot;</span>;</span><br><span class="line">myObj[rand]             = <span class="string">&quot;Random Number&quot;</span>;</span><br><span class="line">myObj[obj]              = <span class="string">&quot;Object&quot;</span>;</span><br><span class="line">myObj[<span class="string">&quot;&quot;</span>]               = <span class="string">&quot;Even an empty string&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(myObj);</span><br></pre></td></tr></table></figure>

<p>请注意，方括号中的所有键都将转换为字符串类型，因为 JavaScript 中的对象只能使用 String 类型作为键类型。例如，在上面的代码中，当将键 obj 添加到 myObj 时，JavaScript 将调用 obj.toString() 方法，并将此结果字符串用作新键。</p>
<p>你也可以通过存储在变量中的字符串来访问属性：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> propertyName = <span class="string">&quot;make&quot;</span>;</span><br><span class="line">myCar[propertyName] = <span class="string">&quot;Ford&quot;</span>;</span><br><span class="line"></span><br><span class="line">propertyName = <span class="string">&quot;model&quot;</span>;</span><br><span class="line">myCar[propertyName] = <span class="string">&quot;Mustang&quot;</span>;</span><br></pre></td></tr></table></figure>

<p>你<strong>可以在 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#for...in_statement">for…in</a> 语句中使用方括号标记以枚举一个对象的所有属性</strong>。为了展示它如何工作，下面的函数当你将对象及其名称作为参数传入时，显示对象的属性：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">showProps</span>(<span class="params">obj, objName</span>) &#123;</span><br><span class="line">  <span class="keyword">var</span> result = <span class="string">&quot;&quot;</span>;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> obj) &#123;</span><br><span class="line">    <span class="keyword">if</span> (obj.<span class="title function_">hasOwnProperty</span>(i)) &#123;</span><br><span class="line">        result += objName + <span class="string">&quot;.&quot;</span> + i + <span class="string">&quot; = &quot;</span> + obj[i] + <span class="string">&quot;\n&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因而，对于函数调用 <code>showProps(myCar, &quot;myCar&quot;)</code> 将返回以下值：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">myCar.<span class="property">make</span> = <span class="title class_">Ford</span></span><br><span class="line">myCar.<span class="property">model</span> = <span class="title class_">Mustang</span></span><br><span class="line">myCar.<span class="property">year</span> = <span class="number">1969</span></span><br></pre></td></tr></table></figure>

<h2 id="枚举一个对象的所有属性"><a href="#枚举一个对象的所有属性" class="headerlink" title="枚举一个对象的所有属性"></a>枚举一个对象的所有属性</h2><p>从 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/JavaScript/ECMAScript_5_support_in_Mozilla">ECMAScript 5</a> 开始，有三种原生的方法用于列出或枚举对象的属性：</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...in">for…in</a> 循环 该方法依次访问一个对象及其原型链中所有可枚举的属性。</li>
<li><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/keys">Object.keys(o)</a> 该方法返回对象 <code>o</code> 自身包含（不包括原型中）的所有可枚举属性的名称的数组。</li>
<li><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames">Object.getOwnPropertyNames(o)</a> 该方法返回对象 <code>o</code> 自身包含（不包括原型中）的所有属性 (无论是否可枚举) 的名称的数组。</li>
</ul>
<p>在 ECMAScript 5 之前，没有原生的方法枚举一个对象的所有属性。然而，可以通过以下函数完成：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">listAllProperties</span>(<span class="params">o</span>)&#123;</span><br><span class="line">  <span class="keyword">var</span> objectToInspect;</span><br><span class="line">  <span class="keyword">var</span> result = [];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span>(objectToInspect = o; objectToInspect !== <span class="literal">null</span>; objectToInspect = <span class="title class_">Object</span>.<span class="title function_">getPrototypeOf</span>(objectToInspect))&#123;</span><br><span class="line">    result = result.<span class="title function_">concat</span>(<span class="title class_">Object</span>.<span class="title function_">getOwnPropertyNames</span>(objectToInspect));</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这在展示“隐藏”（在原型中的不能通过对象访问的属性，因为另一个同名的属性存在于原型链的早期）的属性时很有用。如果只想列出可访问的属性，那么只需要去除数组中的重复元素即可。</p>
<h2 id="创建新对象-notebook"><a href="#创建新对象-notebook" class="headerlink" title="创建新对象:notebook:"></a>创建新对象:notebook:</h2><p>JavaScript 拥有一系列预定义的对象。另外，你可以创建你自己的对象。从 JavaScript 1.2 之后，你可以通过<strong>对象初始化器（Object Initializer）</strong>创建对象。或者你可以创建一个构造函数并使用该函数和 <code>new</code> 操作符初始化对象。</p>
<h3 id="使用对象初始化器"><a href="#使用对象初始化器" class="headerlink" title="使用对象初始化器"></a>使用对象初始化器</h3><p>除了通过构造函数创建对象之外，你也可以通过对象初始化器创建对象。使用对象初始化器也被称作通过字面值创建对象。对象初始化器与 C++ 术语相一致。</p>
<p>通过对象初始化器创建对象的语法如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123; <span class="attr">property_1</span>:   value_1,   <span class="comment">// property_# 可以是一个标识符...</span></span><br><span class="line">            <span class="number">2</span>:            value_2,   <span class="comment">// 或一个数字...</span></span><br><span class="line">           [<span class="string">&quot;property&quot;</span> +<span class="number">3</span>]: value_3,  <span class="comment">//  或一个可计算的 key 名...</span></span><br><span class="line">            <span class="comment">// ...,</span></span><br><span class="line">            <span class="string">&quot;property n&quot;</span>: value_n &#125;; <span class="comment">// 或一个字符串</span></span><br></pre></td></tr></table></figure>

<p>这里 <code>obj</code> 是新对象的名称，每一个 <code>property_i</code> 是一个标识符（可以是一个名称、数字或字符串字面量），并且每个 <code>value_i</code> 是一个其值将被赋予 <code>property_i</code> 的表达式。<code>obj</code> 与赋值是可选的；如果你不需要在其他地方引用对象，你就不需要将它赋给一个变量。（注意在接受一条语句的地方，你可能需要将对象字面量括在括号里，从而避免将字面量与块语句相混淆）</p>
<p>如果一个对象是通过在顶级脚本的对象初始化器创建的，则 JavaScript 在每次遇到包含该对象字面量的表达式时都会创建对象。同样的，在函数中的初始化器在每次函数调用时也会被创建。</p>
<p>下面的语句只有当 <code>cond</code> 表达式的值为 <code>true</code> 时创建对象并将其赋给变量 <code>x</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (cond) <span class="keyword">var</span> x = &#123;<span class="attr">hi</span>: <span class="string">&quot;there&quot;</span>&#125;;</span><br></pre></td></tr></table></figure>

<p>下例创建了有三个属性的 <code>myHonda</code> 对象。注意它的 <code>engine</code> 属性也是一个拥有自己属性的对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> myHonda = &#123;<span class="attr">color</span>: <span class="string">&quot;red&quot;</span>, <span class="attr">wheels</span>: <span class="number">4</span>, <span class="attr">engine</span>: &#123;<span class="attr">cylinders</span>: <span class="number">4</span>, <span class="attr">size</span>: <span class="number">2.2</span>&#125;&#125;;</span><br></pre></td></tr></table></figure>

<p>你也可以用对象初始化器来创建数组。参见<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Grammar_and_types#%E6%95%B0%E7%BB%84%E5%AD%97%E9%9D%A2%E9%87%8F_array_literals">数组字面量</a></p>
<p>在 JavaScript 1.1 及更早版本中，你不能使用对象初始化器。你只能通过使用构造函数或其他对象的函数来创建对象。参见 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Working_with_Objects#%E4%BD%BF%E7%94%A8%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0">使用构造函数</a>.</p>
<h3 id="使用构造函数"><a href="#使用构造函数" class="headerlink" title="使用构造函数"></a>使用构造函数</h3><p>作为另一种方式，你可以通过两步来创建对象：</p>
<ol>
<li>通过创建一个构造函数来定义对象的类型。首字母大写是非常普遍而且很恰当的惯用法。</li>
<li>通过 <code>new</code> 创建对象实例。</li>
</ol>
<p>为了定义对象类型，为对象类型创建一个函数以声明类型的名称、属性和方法。例如，你想为汽车创建一个类型，并且将这类对象称为 <code>car</code> ，并且拥有属性 make, model，和 year，你可以创建如下的函数：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">Car</span>(<span class="params">make, model, year</span>) &#123;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">make</span> = make;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">model</span> = model;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">year</span> = year;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意通过使用 this 将传入函数的值赋给对象的属性。</p>
<p>现在你可以象这样创建一个 <code>mycar</code> 对象：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> mycar = <span class="keyword">new</span> <span class="title class_">Car</span>(<span class="string">&quot;Eagle&quot;</span>, <span class="string">&quot;Talon TSi&quot;</span>, <span class="number">1993</span>);</span><br></pre></td></tr></table></figure>

<p>该创建了 <code>mycar</code> 并且将指定的值赋给它的属性。因而 <code>mycar.make</code> 的值是字符串 “Eagle”， <code>mycar.year</code> 的值是整数 1993，依此类推。</p>
<p>你可以通过调用 <code>new</code> 创建任意数量的 <code>car</code> 对象。例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> kenscar = <span class="keyword">new</span> <span class="title class_">Car</span>(<span class="string">&quot;Nissan&quot;</span>, <span class="string">&quot;300ZX&quot;</span>, <span class="number">1992</span>);</span><br><span class="line"><span class="keyword">var</span> vpgscar = <span class="keyword">new</span> <span class="title class_">Car</span>(<span class="string">&quot;Mazda&quot;</span>, <span class="string">&quot;Miata&quot;</span>, <span class="number">1990</span>);</span><br></pre></td></tr></table></figure>

<p><strong>一个对象的属性值可以是另一个对象</strong>。例如，假设你按如下方式定义了 <code>person</code> 对象：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">Person</span>(<span class="params">name, age, sex</span>) &#123;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">name</span> = name;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">age</span> = age;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">sex</span> = sex;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后按如下方式创建了两个 <code>person</code> 实例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> rand = <span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Rand McKinnon&quot;</span>, <span class="number">33</span>, <span class="string">&quot;M&quot;</span>);</span><br><span class="line"><span class="keyword">var</span> ken = <span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Ken Jones&quot;</span>, <span class="number">39</span>, <span class="string">&quot;M&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>那么，你可以重写 <code>car</code> 的定义以包含一个拥有它的 <code>owner</code> 属性，如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">Car</span>(<span class="params">make, model, year, owner</span>) &#123;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">make</span> = make;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">model</span> = model;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">year</span> = year;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">owner</span> = owner;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>你可以按如下方式创建新对象：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> car1 = <span class="keyword">new</span> <span class="title class_">Car</span>(<span class="string">&quot;Eagle&quot;</span>, <span class="string">&quot;Talon TSi&quot;</span>, <span class="number">1993</span>, rand);</span><br><span class="line"><span class="keyword">var</span> car2 = <span class="keyword">new</span> <span class="title class_">Car</span>(<span class="string">&quot;Nissan&quot;</span>, <span class="string">&quot;300ZX&quot;</span>, <span class="number">1992</span>, ken);</span><br></pre></td></tr></table></figure>

<p>注意在创建新对象时，上面的语句将 <code>rand</code> 和 <code>ken</code> 作为 <code>owner</code> 的参数值，而不是传入字符串字面量或整数值。接下来你如果想找出 car2 的拥有者的姓名，你可以访问如下属性：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">car2.<span class="property">owner</span>.<span class="property">name</span></span><br></pre></td></tr></table></figure>

<p>注意你总是可以为之前定义的对象增加新的属性。例如，语句</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">car1.<span class="property">color</span> = <span class="string">&quot;black&quot;</span>;</span><br></pre></td></tr></table></figure>

<p>为 <code>car1</code> 增加了 <code>color</code> 属性，并将其值设为 “black.” 然而，这并不影响其他的对象。想要为某个类型的所有对象增加新属性，你必须将属性加入到 <code>car</code> 对象类型的定义中。</p>
<h3 id="使用-Object-create-方法"><a href="#使用-Object-create-方法" class="headerlink" title="使用 Object.create 方法"></a>使用 Object.create 方法</h3><p>对象也可以用 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/create"><code>Object.create()</code></a> 方法创建。<strong>该方法非常有用，因为它允许你为创建的对象选择一个原型对象，而不用定义构造函数</strong>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Animal properties and method encapsulation</span></span><br><span class="line"><span class="keyword">var</span> <span class="title class_">Animal</span> = &#123;</span><br><span class="line">  <span class="attr">type</span>: <span class="string">&quot;Invertebrates&quot;</span>, <span class="comment">// 属性默认值</span></span><br><span class="line">  displayType : <span class="keyword">function</span>(<span class="params"></span>) &#123;  <span class="comment">// 用于显示 type 属性的方法</span></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">type</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建一种新的动物——animal1</span></span><br><span class="line"><span class="keyword">var</span> animal1 = <span class="title class_">Object</span>.<span class="title function_">create</span>(<span class="title class_">Animal</span>);</span><br><span class="line">animal1.<span class="title function_">displayType</span>(); <span class="comment">// Output:Invertebrates</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建一种新的动物——Fishes</span></span><br><span class="line"><span class="keyword">var</span> fish = <span class="title class_">Object</span>.<span class="title function_">create</span>(<span class="title class_">Animal</span>);</span><br><span class="line">fish.<span class="property">type</span> = <span class="string">&quot;Fishes&quot;</span>;</span><br><span class="line">fish.<span class="title function_">displayType</span>(); <span class="comment">// Output:Fishes</span></span><br></pre></td></tr></table></figure>

<h2 id="继承"><a href="#继承" class="headerlink" title="继承"></a>继承</h2><p>所有的 JavaScript 对象至少继承于一个对象。被继承的对象被称作原型，并且继承的属性可通过构造函数的 <code>prototype</code> 对象找到。查看更多详细 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">Inheritance and the prototype chain</a></p>
<h2 id="对象属性索引"><a href="#对象属性索引" class="headerlink" title="对象属性索引"></a>对象属性索引</h2><p>在 JavaScript 1.0 中，你可以通过名称或序号访问一个属性。但是<strong>在 JavaScript 1.1 及之后版本中，如果你最初使用名称定义了一个属性，则你必须通过名称来访问它；而如果你最初使用序号来定义一个属性，则你必须通过索引来访问它</strong>。</p>
<p>这个限制发生在你通过构造函数创建一个对象和它的属性（就象我们之前通过 <code>Car</code> 对象类型所做的那样）并且显式地定义了单独的属性（如 <code>myCar.color = &quot;red&quot;</code>）之时。如果你最初使用索引定义了一个对象属性，例如 <code>myCar[5] = &quot;25&quot;</code>，则你只可能通过 <code>myCar[5]</code> 引用它。</p>
<p><strong>这条规则的例外是从与 HTML 对应的对象，例如 <code>forms</code> 数组</strong>。对于这些数组的元素，你总是既可以通过其序号（依据其在文档中出现的顺序），也可以按照其名称（如果有的话）访问它。举例而言，如果文档中的第二个 <code>&lt;form&gt;</code> 标签有一个 <code>NAME</code> 属性且值为 <code>&quot;myForm&quot;</code>，访问该 <code>form</code> 的方式可以是 <code>document.forms[1]</code>，<code>document.forms[&quot;myForm&quot;]</code> 或 <code>document.myForm</code>。</p>
<h3 id="为对象类型定义属性"><a href="#为对象类型定义属性" class="headerlink" title="为对象类型定义属性"></a>为对象类型定义属性</h3><p>你可以通过 <code>prototype</code>属性为之前定义的对象类型增加属性。这为该类型的所有对象，而不是仅仅一个对象增加了一个属性。下面的代码为所有类型为 <code>car</code> 的对象增加了 <code>color</code> 属性，然后为对象 <code>car1</code> 的 <code>color</code> 属性赋值：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Car</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">color</span> = <span class="literal">null</span>;</span><br><span class="line">car1.<span class="property">color</span> = <span class="string">&quot;black&quot;</span>;</span><br></pre></td></tr></table></figure>

<p>参见 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference">JavaScript Reference</a> 中 Function 对象的 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype"><code>prototype</code> 属性 (en-US)</a> 。</p>
<h2 id="定义方法"><a href="#定义方法" class="headerlink" title="定义方法"></a>定义方法</h2><p>一个<em>方法</em> 是关联到某个对象的函数，或者简单地说，一个方法是一个值为某个函数的对象属性。定义方法就像定义普通的函数，除了它们必须被赋给对象的某个属性。查看 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a>了解更多详情例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">objectName.<span class="property">methodname</span> = function_name;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> myObj = &#123;</span><br><span class="line">  <span class="attr">myMethod</span>: <span class="keyword">function</span>(<span class="params">params</span>) &#123;</span><br><span class="line">    <span class="comment">// ...do something</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 或者 这样写也可以</span></span><br><span class="line"></span><br><span class="line">  <span class="title function_">myOtherMethod</span>(<span class="params">params</span>) &#123;</span><br><span class="line">    <span class="comment">// ...do something else</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>这里 <code>objectName</code> 是一个已经存在的对象，<code>methodname</code> 是方法的名称，而 <code>function_name</code> 是函数的名称。</p>
<p>你可以在对象的上下文中象这样调用方法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">object.<span class="title function_">methodname</span>(params);</span><br></pre></td></tr></table></figure>

<p>你可以在对象的构造函数中包含方法定义来为某个对象类型定义方法。例如，你可以为之前定义的 <code>car</code> 对象定义一个函数格式化并显示其属性：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">displayCar</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">var</span> result = <span class="string">`A Beautiful <span class="subst">$&#123;<span class="variable language_">this</span>.year&#125;</span> <span class="subst">$&#123;<span class="variable language_">this</span>.make&#125;</span> <span class="subst">$&#123;<span class="variable language_">this</span>.model&#125;</span>`</span>;</span><br><span class="line">  <span class="title function_">pretty_print</span>(result);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里 <code>pretty_print</code> 是一个显示横线和一个字符串的函数。注意使用 this 指代方法所属的对象。</p>
<p>你可以在对象定义中通过增加下述语句将这个函数变成 <code>Car</code> 的方法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable language_">this</span>.<span class="property">displayCar</span> = displayCar;</span><br></pre></td></tr></table></figure>

<p>因此，<code>Car</code> 的完整定义看上去将是：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">Car</span>(<span class="params">make, model, year, owner</span>) &#123;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">make</span> = make;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">model</span> = model;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">year</span> = year;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">owner</span> = owner;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">displayCar</span> = displayCar;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后你可以按如下方式为每个对象调用 <code>displayCar</code> 方法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">car1.<span class="title function_">displayCar</span>();</span><br><span class="line">car2.<span class="title function_">displayCar</span>();</span><br></pre></td></tr></table></figure>

<h2 id="通过-this-引用对象"><a href="#通过-this-引用对象" class="headerlink" title="通过 this 引用对象"></a>通过 <code>this</code> 引用对象</h2><p>JavaScript 有一个特殊的关键字 <code>this</code>，它可以在方法中使用以指代当前对象。例如，假设你有一个名为 <code>validate</code> 的函数，它根据给出的最大与最小值检查某个对象的 <code>value</code> 属性：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">validate</span>(<span class="params">obj, lowval, hival</span>) &#123;</span><br><span class="line">  <span class="keyword">if</span> ((obj.<span class="property">value</span> &lt; lowval) || (obj.<span class="property">value</span> &gt; hival)) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&quot;Invalid Value!&quot;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后，你可以在每个元素的 <code>onchange</code> 事件处理器中调用 <code>validate</code>，并通过 <code>this</code> 传入相应元素，代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type=<span class="string">&quot;text&quot;</span> name=<span class="string">&quot;age&quot;</span> size=<span class="string">&quot;3&quot;</span></span><br><span class="line">  onChange=<span class="string">&quot;validate(this, 18, 99)&quot;</span>&gt;</span><br></pre></td></tr></table></figure>

<p>总的说来， <code>this</code> 在一个方法中指调用的对象。</p>
<p>当与 <code>form</code> 属性一起使用时，<code>this</code>可以指代当前对象的父窗体。在下面的例子中，窗体 <code>myForm</code> 包含一个 <code>Text</code> 对象和一个按钮，当用户点击按键，<code>Text</code> 对象的值被设为窗体的名称。按钮的 <code>onclick</code> 事件处理器使用 <code>this.form</code> 以指代其父窗体，即 <code>myForm</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;form name=<span class="string">&quot;myForm&quot;</span>&gt;</span><br><span class="line">&lt;p&gt;&lt;label&gt;Form name:&lt;input type=&quot;text&quot; name=&quot;text1&quot; value=&quot;Beluga&quot;&gt;&lt;/label&gt;</span><br><span class="line">&lt;p&gt;&lt;input name=&quot;button1&quot; type=&quot;button&quot; value=&quot;Show Form Name&quot;</span><br><span class="line">     onclick=&quot;this.form.text1.value = this.form.name&quot;&gt;</span><br><span class="line">&lt;/p&gt;</span><br><span class="line">&lt;/form&gt;</span><br></pre></td></tr></table></figure>

<h2 id="定义-getter-与-setter"><a href="#定义-getter-与-setter" class="headerlink" title="定义 getter 与 setter"></a>定义 getter 与 setter</h2><p>一个 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/get">getter</a> 是一个获取某个特定属性的值的方法。一个 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/set">setter</a> 是一个设定某个属性的值的方法。你可以为预定义的或用户定义的对象定义 getter 和 setter 以支持新增的属性。定义 getter 和 setter 的语法采用对象字面量语法。</p>
<p>下面例子描述了 getter 和 setter 是如何为用户定义的对象 <code>o</code> 工作的。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> o = &#123;</span><br><span class="line">  <span class="attr">a</span>: <span class="number">7</span>,</span><br><span class="line">  <span class="keyword">get</span> <span class="title function_">b</span>() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">a</span> + <span class="number">1</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="keyword">set</span> <span class="title function_">c</span>(<span class="params">x</span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">a</span> = x / <span class="number">2</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(o.<span class="property">a</span>); <span class="comment">// 7</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(o.<span class="property">b</span>); <span class="comment">// 8</span></span><br><span class="line">o.<span class="property">c</span> = <span class="number">50</span>;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(o.<span class="property">a</span>); <span class="comment">// 25</span></span><br></pre></td></tr></table></figure>

<p><code>o</code> 对象的属性如下：</p>
<ul>
<li><code>o.a</code> — 数字</li>
<li><code>o.b</code> — 返回 <code>o.a</code> + 1 的 getter</li>
<li><code>o.c</code> — 由 <code>o.c 的值所设置 o.a 值的</code> setter</li>
</ul>
<p>请注意在一个对象字面量语法中定义 getter 和 setter 使用”[gs]et property()”的方式（相比较于__define[GS]etter__) 时，并不是获取和设置某个属性自身，容易让人误以为是”[gs]et propertyName(){ }”这样错误的使用方法。定义一个 getter 或 setter 函数使用语法”[gs]et property()”，定义一个已经声明的函数作为的 getter 和 setter 方法，使用<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty"><code>Object.defineProperty</code></a>(或者 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__"><code>Object.prototype.__defineGetter__</code> (en-US)</a> 旧语法回退)</p>
<p>下面这个例子展示使用 getter 和 setter 方法扩展 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date"><code>Date</code></a>原型，为预定义好的 Date 类添加一个 year 的属性。定义属性 year 的 getter 和 setter 方法用到了 Date 类中已存在的 getFullYear 和 setFullYear 方法。</p>
<p>定义属性 year 的 getter 和 setter：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> d = <span class="title class_">Date</span>.<span class="property"><span class="keyword">prototype</span></span>;</span><br><span class="line"><span class="title class_">Object</span>.<span class="title function_">defineProperty</span>(d, <span class="string">&quot;year&quot;</span>, &#123;</span><br><span class="line">  <span class="attr">get</span>: <span class="keyword">function</span>(<span class="params"></span>) &#123; <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">getFullYear</span>() &#125;,</span><br><span class="line">  <span class="attr">set</span>: <span class="keyword">function</span>(<span class="params">y</span>) &#123; <span class="variable language_">this</span>.<span class="title function_">setFullYear</span>(y) &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>通过一个 Date 对象使用 getter 和 setter:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> now = <span class="keyword">new</span> <span class="title class_">Date</span>();</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(now.<span class="property">year</span>); <span class="comment">// 2000</span></span><br><span class="line">now.<span class="property">year</span> = <span class="number">2001</span>; <span class="comment">// 987617605170</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(now);</span><br><span class="line"><span class="comment">// Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001</span></span><br></pre></td></tr></table></figure>

<p>原则上，getter 和 setter 既可以：</p>
<ul>
<li>使用 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Working_with_Objects#%E4%BD%BF%E7%94%A8%E5%AF%B9%E8%B1%A1%E5%88%9D%E5%A7%8B%E5%8C%96%E5%99%A8">使用对象初始化器</a> 定义</li>
<li>也可以之后随时使用 getter 和 setter 添加方法添加到任何对象</li>
</ul>
<p>当使用 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Working_with_Objects#%E4%BD%BF%E7%94%A8%E5%AF%B9%E8%B1%A1%E5%88%9D%E5%A7%8B%E5%8C%96%E5%99%A8">使用对象初始化器</a> 的方式定义 getter 和 setter 时，只需要在 getter 方法前加 get，在 setter 方法前加 set，当然，getter 方法必须是无参数的，setter 方法只接受一个参数 (设置为新值），例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> o = &#123;</span><br><span class="line">  <span class="attr">a</span>: <span class="number">7</span>,</span><br><span class="line">  <span class="keyword">get</span> <span class="title function_">b</span>() &#123; <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">a</span> + <span class="number">1</span>; &#125;,</span><br><span class="line">  <span class="keyword">set</span> <span class="title function_">c</span>(<span class="params">x</span>) &#123; <span class="variable language_">this</span>.<span class="property">a</span> = x / <span class="number">2</span>; &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>使用 Object.defineProperties 的方法，同样也可以对一个已创建的对象在任何时候为其添加 getter 或 setter 方法。这个方法的第一个参数是你想定义 getter 或 setter 方法的对象，第二个参数是一个对象，这个对象的属性名用作 getter 或 setter 的名字，属性名对应的属性值用作定义 getter 或 setter 方法的函数，下面是一个例子定义了和前面例子一样的 getter 和 setter 方法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> o = &#123; <span class="attr">a</span>:<span class="number">0</span> &#125;</span><br><span class="line"></span><br><span class="line"><span class="title class_">Object</span>.<span class="title function_">defineProperties</span>(o, &#123;</span><br><span class="line">    <span class="string">&quot;b&quot;</span>: &#123; <span class="attr">get</span>: <span class="keyword">function</span> (<span class="params"></span>) &#123; <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">a</span> + <span class="number">1</span>; &#125; &#125;,</span><br><span class="line">    <span class="string">&quot;c&quot;</span>: &#123; <span class="attr">set</span>: <span class="keyword">function</span> (<span class="params">x</span>) &#123; <span class="variable language_">this</span>.<span class="property">a</span> = x / <span class="number">2</span>; &#125; &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">o.<span class="property">c</span> = <span class="number">10</span> <span class="comment">// Runs the setter, which assigns 10 / 2 (5) to the &#x27;a&#x27; property</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(o.<span class="property">b</span>) <span class="comment">// Runs the getter, which yields a + 1 or 6</span></span><br></pre></td></tr></table></figure>

<p>这两种定义方式的选择取决于你的编程风格和手头的工作量。当你定义一个原型准备进行初始化时，可以选择第一种方式，这种方式更简洁和自然。但是，当你需要添加 getter 和 setter 方法 —— 因为并没有编写原型或者特定的对象 ——使用第二种方式更好。第二种方式可能更能表现 JavaScript 语法的动态特性——但也会使代码变得难以阅读和理解。</p>
<h2 id="删除属性"><a href="#删除属性" class="headerlink" title="删除属性"></a>删除属性</h2><p>你可以用 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/delete"><code>delete</code></a> 操作符删除一个<strong>不是继承而来</strong>的属性。下面的例子说明如何删除一个属性：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Creates a new object, myobj, with two properties, a and b.</span></span><br><span class="line"><span class="keyword">var</span> myobj = <span class="keyword">new</span> <span class="title class_">Object</span>;</span><br><span class="line">myobj.<span class="property">a</span> = <span class="number">5</span>;</span><br><span class="line">myobj.<span class="property">b</span> = <span class="number">12</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//Removes the a property, leaving myobj with only the b property.</span></span><br><span class="line"><span class="keyword">delete</span> myobj.<span class="property">a</span>;</span><br></pre></td></tr></table></figure>

<p>如果一个全局变量不是用 <code>var</code> 关键字声明的话，你也可以用 <code>delete</code> 删除它：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">g = <span class="number">17</span>;</span><br><span class="line"><span class="keyword">delete</span> g;</span><br></pre></td></tr></table></figure>

<h2 id="比较对象"><a href="#比较对象" class="headerlink" title="比较对象"></a>比较对象</h2><p>在 JavaScript 中 objects 是一种引用类型。两个独立声明的对象永远也不会相等，即使他们有相同的属性，只有在比较一个对象和这个对象的引用时，才会返回 true.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 两个变量，两个具有同样的属性、但不相同的对象</span></span><br><span class="line"><span class="keyword">var</span> fruit = &#123;<span class="attr">name</span>: <span class="string">&quot;apple&quot;</span>&#125;;</span><br><span class="line"><span class="keyword">var</span> fruitbear = &#123;<span class="attr">name</span>: <span class="string">&quot;apple&quot;</span>&#125;;</span><br><span class="line"></span><br><span class="line">fruit == fruitbear <span class="comment">// return false</span></span><br><span class="line">fruit === fruitbear <span class="comment">// return false</span></span><br></pre></td></tr></table></figure>

<p><strong>备注：</strong> “&#x3D;&#x3D;&#x3D;” 运算符用来检查数值是否相等：1 &#x3D;&#x3D;&#x3D; “1”返回 false，而 1 &#x3D;&#x3D; “1” 返回 true</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 两个变量，同一个对象</span></span><br><span class="line"><span class="keyword">var</span> fruit = &#123;<span class="attr">name</span>: <span class="string">&quot;apple&quot;</span>&#125;;</span><br><span class="line"><span class="keyword">var</span> fruitbear = fruit;  <span class="comment">// 将 fruit 的对象引用 (reference) 赋值给 fruitbear</span></span><br><span class="line">                        <span class="comment">// 也称为将 fruitbear“指向”fruit 对象</span></span><br><span class="line"><span class="comment">// fruit 与 fruitbear 都指向同样的对象</span></span><br><span class="line">fruit == fruitbear <span class="comment">// return true</span></span><br><span class="line">fruit === fruitbear <span class="comment">// return true</span></span><br></pre></td></tr></table></figure>

<p>了解更多关于比较操作符的用法，查看 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators">Comparison operators (en-US)</a>.</p>
<hr>

        
            <div class="donate-container">
    <div class="donate-button">
        <button id="donate-button">赞赏</button>
    </div>
    <div class="donate-img-container hide" id="donate-img-container">
        <img id="donate-img" src="" data-src="/myblog/img/donate.jpg">
        <p> 感谢鼓励 </p>
    </div>
</div>
        
        <br />
        <div id="comment-container">
        </div>
        <div id="disqus_thread"></div>
        <div id="lv-container"></div>
        <div class="giscus"></div>
    </div>
</div>

    </div>
</div>


<footer class="footer">
    <ul class="list-inline text-center">
        
        

        

        

        
        <li>
            <a target="_blank"  href="https://github.com/samuel-24276">
                            <span class="fa-stack fa-lg">
                                <i class="iconfont icon-github"></i>
                            </span>
            </a>
        </li>
        

        

    </ul>
    
    <p>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://github.com/samuel-24276">samuel-24276&#39;s Page</a></span>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/">北京-未备案</a></span>
        <span>/</span>
        
        <span><a href="#">返回顶部</a></span>
        <span>/</span>
        
    </p>
    
    <p>
        <span id="busuanzi_container_site_pv">
            <span id="busuanzi_value_site_pv"></span>PV
        </span>
        <span id="busuanzi_container_site_uv">
            <span id="busuanzi_value_site_uv"></span>UV
        </span>
        Created By <a target="_blank" rel="noopener" href="https://hexo.io/">Hexo</a>  Theme <a target="_blank" rel="noopener" href="https://github.com/aircloud/hexo-theme-aircloud">AirCloud</a></p>
</footer>




</body>

<script>
    // We expose some of the variables needed by the front end
    window.hexo_search_path = "search.json"
    window.hexo_root = "/myblog/"
    window.isPost = true
</script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<script src="/myblog/js/index.js"></script>

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>






    <script type="text/javascript">
       (function() {
           if (typeof LivereTower === 'function') { return; }

           var j, d = document.getElementById('lv-container');

           d.setAttribute('data-id','city');
           d.setAttribute('data-uid' , 'MTAyMC80OTA5OC8yNTU5Mw==');

           j = document.createElement('script');
           j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
           j.async = true;

           d.appendChild(j);
       })();
    </script>
    <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
    </div>

</html>
